﻿// Parts Copyright 2008 Newgrove Consultants Limited
// Modified By John Diss 
// From original work:
//
// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System.Data.SqlTypes;
using GeoAPI.Geometries;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;

public partial class UserDefinedFunctions
{
    /// <summary>
    /// PostGIS docs:
    /// 
    /// This function returns a bounding box expanded in all directions from the 
    /// bounding box of the input geometry, by an amount specified in the second argument.
    /// 
    /// Very useful for distance() queries, to add an index filter to the query.
    /// 
    /// </summary>
    /// <remarks>
    /// Used by IsWithinDistanceQuery
    /// </remarks>
    /// <param name="ewkb"></param>
    /// <param name="distance"></param>
    /// <returns></returns>
    [SqlFunction(IsDeterministic = true)]
    public static SqlBytes Expand(SqlBytes ewkb, SqlDouble distance)
    {
        IGeometry geometry = ConvertGeometry.ToGeometry(ewkb);

        if (geometry != null && !distance.IsNull)
        {
            IExtents envelope = geometry.Extents;

            IExtents envelopeGrown = GeometryUtilities.ExpandBy(envelope, distance.Value);

            return ConvertGeometry.ToSqlBytes(
                Global
                    .Services
                    .GeometryFactory
                    .ToGeometry(envelopeGrown)
                , GeometryUtilities.MsSqlSpatialSrid(geometry));
        }
        return SqlBytes.Null;
    }
} ;